package com.woniuxy.config;

import com.woniuxy.core.mapper.ShopOrderMapper;
import com.woniuxy.core.service.ShopOrderService;
import com.woniuxy.entity.ShopOrder;
import com.woniuxy.enums.order.ShopOrderStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author hq
 * @Date 2025/7/15$ 11:39$
 * @Description TODO
 * @Params $
 * @Return $
 **/
@Component
@Slf4j
public class OrderTimeoutConsumer {
    @Autowired
    private ShopOrderService shopOrderService;

    @RabbitListener(queues = RabbitMQConfig.ORDER_DEAD_LETTER_QUEUE)
    public void handleOrderTimeout(String orderNumber) {
        try {
            log.info("处理超时订单，订单ID：{}", orderNumber);

            // 查询订单
            ShopOrder order = shopOrderService.getByOrderByNumber(orderNumber);
            if (order == null) {
                log.warn("订单不存在，订单ID：{}", orderNumber);
                return;
            }

            // 检查订单状态
            if (order.getStatus() != ShopOrderStatus.PENDING.getCode()) {
                log.info("订单状态已变更，无需关闭，订单ID：{}，当前状态：{}",
                        orderNumber, order.getStatus());
                return;
            }
            // 检查订单是否已支付
            if (order.getPaymentTime() != null) {
                log.info("订单已支付，关闭，订单ID：{}", orderNumber);
            }
            // 关闭订单
            shopOrderService.closeOrder(orderNumber);
            log.info("订单{}已超时关闭", orderNumber);

        } catch (NumberFormatException e) {
            log.error("订单ID格式错误：{}", orderNumber, e);
        } catch (Exception e) {
            log.error("处理超时订单异常，订单ID：{}", orderNumber, e);
        }
    }
}
